package com.cuitrip;

import com.csvreader.CsvReader;
import com.cuitrip.config.Config;
import com.cuitrip.mode.KeyTransform;
import com.cuitrip.mode.Language;
import com.cuitrip.mode.Rule;
import com.cuitrip.util.FileUtil;
import com.cuitrip.util.PrintUtil;
import com.cuitrip.util.TextUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * Created by MiJack on 2015/11/21.
 */
public class LanguageTool {
    private Config config;

    int i = 0;

    public void setConfig(Config config) {
        this.config = config;
    }

    public void startWork() throws IOException {
        CsvReader r = new CsvReader(config.getFileName(), ',', Charset.forName(config.getFileEncoding()));
        handHead();
        r.readHeaders();
        //判断是否有老的key
        boolean oldKeyEnable = config.isOldKeyEnable();
        Map<String, String> keyMap = new HashMap<String, String>();
        while (r.readRecord()) {
            i++;
            //负责读取key和values
            String key = r.get(config.getKeyIndex());
            PrintUtil.print(i + "：key -> " + key);
            Map<Integer, String> values = new HashMap<Integer, String>();
            for (Integer integer : config.getLanguageMap().keySet()) {
                values.put(integer, r.get(integer));
            }
            values.put(config.getOldKeyIndex(), r.get(config.getOldKeyIndex()));
            String commit = r.get(config.getCommitIndex());
            //判断是否为注释
            if (TextUtil.isCommit(config, commit)) {
                appendCommit(commit);
                continue;
            } else {
                appendValue(key, values);
            }
            //判断是否有老的key
            if (oldKeyEnable) {
                int oldKeyIndex = config.getOldKeyIndex();
                String oldKey = r.get(oldKeyIndex);
                keyMap.put(oldKey, key);
            }
        }
        //给android文件添加尾部
        handEnd();
        r.close();
        PrintUtil.print("----------------------------------------");
        for (Map.Entry<String, String> entry : keyMap.entrySet()) {
            String oldK = entry.getKey();
            String newK = entry.getValue();
            if (TextUtil.isEmpty(oldK)) {
                PrintUtil.print("add: " + newK);
            } else {
                PrintUtil.print("change: " + oldK + " -> " + newK);
            }
        }
    }

    private void appendValue(final String key, final Map<Integer, String> values) throws IOException {
        traverseFiles(new FileCallBack() {

            public void call(String fileName, Rule rule, Language language) throws IOException {
                String value = values.get(language.getIndex());
                String oldKey = values.get(config.getOldKeyIndex());
                //value的replace
                for (Map.Entry<String, String> entry : rule.getReplaceMap().entrySet()) {
                    value = value.replace(entry.getKey(), entry.getValue());
                }
                String k = key;
                value = value.replace("\r\n", "{TEMP}").replace("\n", "\\n").replace("{TEMP}", "\\n");
                String valueSample="";
                KeyTransform transform = rule.getTransform();
                if (TextUtil.isEmpty(oldKey)) {
                    valueSample=rule.getOutputSample("add");
                } else if (!key.equalsIgnoreCase(oldKey)) {
                    valueSample=rule.getOutputSample("change");
                }else{
                    valueSample=rule.getOutputSample("default");
                }
                String output =valueSample.replace("{$old_key}",transform.Transform(oldKey)).replace("{$new_key}",transform.Transform(key)).replace("{$value}",value);
                FileUtil.appendLine(fileName, output);
            }
        });
    }

    private void appendCommit(final String commit) throws IOException {
        traverseFiles(new FileCallBack() {

            public void call(String fileName, Rule rule, Language language) throws IOException {
                if (TextUtil.isEmpty(commit)) {
                    return;
                }
                FileUtil.appendLine(fileName, String.format(rule.getCommitSample(), commit));
            }
        });
    }

    public void traverseFiles(FileCallBack callBack) throws IOException {
        Map<Integer, Language> map = config.getLanguageMap();
        for (Rule rule : config.getRuleList()) {
            for (Integer index : map.keySet()) {
                //文件头部的信息在rule类中
                //文件名
                Language language = map.get(index);
                String fileName = FileUtil.buildFileName(config, rule, language);
                FileUtil.checkFile(fileName);
                callBack.call(fileName, rule, language);
            }
        }
    }

    private void handHead() throws IOException {
        traverseFiles(new FileCallBack() {

            public void call(String fileName, Rule rule, Language language) throws IOException {
                FileUtil.appendLine(fileName, rule.getFileHead());
            }
        });
//        Map<Integer, Language> map = config.getLanguageMap();
//        for (Rule rule : config.getRuleList())
//            for (Integer index : map.keySet()) {
//                //文件头部的信息在rule类中
//                //文件名
//                Language language = map.get(index);
//                String fileName = FileUtil.buildFileName(config, rule, language);
//                FileUtil.checkFile(fileName);
//
//            }
    }

    private void handEnd() throws IOException {
        traverseFiles(new FileCallBack() {
            public void call(String fileName, Rule rule, Language language) throws IOException {
                FileUtil.appendLine(fileName, rule.getFileEnd());
            }
        });
    }
}
